#!/bin/bash

# 批量停止一主二备拓扑的所有虚拟机

set -e

SOURCE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SOURCE_DIR/config.conf"

echo "停止一主二备拓扑所有虚拟机..."
echo

# 定义节点（逆序停止，先停worker）
NODES=("${VM_NAME_PREFIX}-worker2" "${VM_NAME_PREFIX}-worker1" "${VM_NAME_PREFIX}-master1")

for vm_name in "${NODES[@]}"; do
    pid_file="$VM_IMAGE_DIR/${vm_name}.pid"
    monitor_file="$VM_IMAGE_DIR/${vm_name}.monitor"
    
    if [ -f "$pid_file" ]; then
        pid=$(cat "$pid_file")
        if kill -0 "$pid" 2>/dev/null; then
            echo "停止 $vm_name (PID: $pid)..."
            # 尝试优雅关机
            if [ -S "$monitor_file" ]; then
                echo "system_powerdown" | socat - "$monitor_file" 2>/dev/null || true
                sleep 3
            fi
            # 如果还在运行，强制终止
            if kill -0 "$pid" 2>/dev/null; then
                kill "$pid" 2>/dev/null || true
                sleep 1
            fi
            rm -f "$pid_file"
            echo "✓ $vm_name 已停止"
        else
            echo "$vm_name 未运行"
            rm -f "$pid_file"
        fi
    else
        echo "$vm_name PID文件不存在"
    fi
done

echo
echo "所有虚拟机已停止"
